import pygame
from typing import Dict
import os

class SoundManager:
    def __init__(self):
        self.sounds: Dict[str, pygame.mixer.Sound] = {}
        self.music_volume = 0.5
        self.sfx_volume = 0.7
        self.load_sounds()
        
        # 添加音效混合设置
        pygame.mixer.set_num_channels(16)  # 允许同时播放多个音效
        self.sound_channels = {}
    
    def load_sounds(self):
        """加载音效"""
        sound_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'assets', 'sounds')
        
        sound_files = {
            'card_play': 'card_play.wav',
            'attack': 'attack.wav',
            'damage': 'damage.wav',
            'victory': 'victory.wav',
            'defeat': 'defeat.wav',
            'button_click': 'button_click.wav',
        }
        
        for name, file in sound_files.items():
            try:
                path = os.path.join(sound_dir, file)
                if os.path.exists(path):
                    self.sounds[name] = pygame.mixer.Sound(path)
                else:
                    print(f"Missing sound file: {file}")
            except Exception as e:
                print(f"Warning: Could not load sound {file}: {e}")
                # 创建一个空的Sound对象作为替代
                self.sounds[name] = pygame.mixer.Sound(buffer=b'\x00' * 44100)  # 1秒的静音
    
    def play_sound(self, name: str, volume: float = None, pitch: float = 1.0):
        """播放音效，支持音量和音调控制"""
        if name in self.sounds:
            sound = self.sounds[name]
            if volume is None:
                volume = self.sfx_volume
            
            # 查找空闲通道
            channel = pygame.mixer.find_channel()
            if channel:
                channel.set_volume(volume)
                channel.play(sound)
                self.sound_channels[name] = channel
    
    def stop_sound(self, name: str):
        """停止指定音效"""
        if name in self.sound_channels:
            self.sound_channels[name].stop()
            del self.sound_channels[name]
    
    def fade_out_music(self, duration: int = 1000):
        """淡出背景音乐"""
        pygame.mixer.music.fadeout(duration)
    
    def play_music(self, name: str):
        """播放背景音乐"""
        try:
            music_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 
                                    'assets', 'music', f'{name}.mp3')
            pygame.mixer.music.load(music_path)
            pygame.mixer.music.set_volume(self.music_volume)
            pygame.mixer.music.play(-1)  # -1表示循环播放
        except:
            print(f"Warning: Could not load music {name}") 